package com.freecloud.plug.redisson.lock;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.concurrent.TimeUnit;

/**
 * redisson分布式锁
 */
public class LockTest {
    private static RedissonClient redissonClient;

    static {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://192.168.10.110:30001");
        redissonClient= Redisson.create(config);
    }

    public static void main(String[] args) throws InterruptedException {
        //设定锁标志
        //会在redis中创建一个Hash，Key是客户端UUID，value是锁重入次数
        RLock rLock = redissonClient.getLock("lockKey");
        // 最多等待100秒、上锁10s以后自动解锁
        if(rLock.tryLock(100,10, TimeUnit.SECONDS)){
            System.out.println("获取锁成功，此时可以查看redis中的数据！");
        }
        //线程等待后可在redis中查到
        Thread.sleep(20000);
        rLock.unlock();

        redissonClient.shutdown();
    }
}
